<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Sensor Data Dashboard</title>
    <link href="{{ url_for('static', filename='css/bootstrap.min.css') }}" rel="stylesheet">
    <style>
      .dashboard-container {
        max-width: 1400px;
        margin: 0 auto;
        padding: 20px;
      }
      .chart-container {
        background: #1e1e2f;
        border-radius: 10px;
        padding: 20px;
        margin-bottom: 30px;
        box-shadow: 0 0 20px rgba(0,0,0,0.1);
        height: 600px;  /* Increased height */
      }
      #sensorChart {
        height: 550px !important;  /* Increased chart height */
      }
      .data-table {
        background: #fff;
        border-radius: 10px;
        box-shadow: 0 0 20px rgba(0,0,0,0.1);
      }
      @media (max-width: 768px) {
        .chart-container {
          height: 400px;
        }
        #sensorChart {
          height: 350px !important;
        }
      }
      @media (max-width: 576px) {
        .chart-container {
          height: 300px;
        }
        #sensorChart {
          height: 250px !important;
        }
      }
    </style>
  </head>
  <body style="background: #f8f9fa;">
    <div class="dashboard-container">
      <h1 class="text-center mb-4" style="color: #2dce89;">Sensor Dashboard</h1>
      
      <div class="row">
        <div class="col-12">
          <div class="chart-container">
            <canvas id="sensorChart"></canvas>
          </div>
        </div>
      </div>

      <div class="row">
        <div class="col-12">
          <div class="data-table">
            <table class="table table-striped">
              <thead>
                <tr>
                  <th width="40%">TS</th>
                  <th>Dev</th>
                  <th>Temp</th>
                  <th>Humi</th>
                </tr>
              </thead>
              <tbody id="dataTableBody">
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>

    <script src="{{ url_for('static', filename='js/jquery-3.7.1.min.js') }}"></script>
    <script src="{{ url_for('static', filename='js/bootstrap.bundle.min.js') }}"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script>
      $(document).ready(function() {
        const ctx = document.getElementById('sensorChart').getContext('2d');
        const chart = new Chart(ctx, {
          type: 'line',
          data: {
            labels: [],
            datasets: [{
              label: 'Temperature (°C)',
              data: [],
              borderColor: '#2dce89',
              fill: false,
              cubicInterpolationMode: 'monotone'  // Smooth curves
            }, {
              label: 'Humidity (%)',
              data: [],
              borderColor: '#5e72e4',
              fill: false,
              yAxisID: 'y1',
              cubicInterpolationMode: 'monotone'  // Smooth curves
            }]
          },
          options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
              x: {
                grid: {
                  color: '#43425d'
                },
                ticks: {
                  color: '#fff'
                }
              },
              y: {
                type: 'linear',
                display: true,
                position: 'left',
                grid: {
                  color: '#43425d'
                },
                ticks: {
                  color: '#2dce89'
                },
                title: {
                  display: true,
                  text: 'Temperature (°C)',
                  color: '#2dce89'
                }
              },
              y1: {
                type: 'linear',
                display: true,
                position: 'right',
                grid: {
                  drawOnChartArea: false,
                },
                ticks: {
                  color: '#5e72e4'
                },
                title: {
                  display: true,
                  text: 'Humidity (%)',
                  color: '#5e72e4'
                }
              }
            },
            plugins: {
              legend: {
                labels: {
                  color: '#fff'
                }
              }
            }
          }
        });

        function updateDashboard() {
            $.get('/api/data')
              .done(function(data) {
                // Update table - show latest 10 records in descending order
                $('#dataTableBody').empty();
                data.slice(-10).reverse().forEach(record => {
                  $('#dataTableBody').append(`
                    <tr>
                      <td>${record.timestamp}</td>
                      <td>${record.device_id.slice(-6)}</td>  <!-- Only last 6 characters -->
                      <td>${record.temperature.toFixed(2)}</td>
                      <td>${record.humidity.toFixed(2)}</td>
                    </tr>
                  `);
                });

                // Update chart - only show latest 20 data points
                const latestData = data.slice(-20);
                const timestamps = latestData.map(r => new Date(r.timestamp).toLocaleTimeString());  // Extract time part
                const temperatures = latestData.map(r => r.temperature);
                const humidities = latestData.map(r => r.humidity);

                chart.data.labels = timestamps;
                chart.data.datasets[0].data = temperatures;
                chart.data.datasets[1].data = humidities;
                chart.update();
              })
              .fail(function(jqXHR, textStatus, errorThrown) {
                console.error('Failed to update dashboard:', textStatus, errorThrown);
              });
        }

        // Initial load
        updateDashboard();
        // Refresh every 5 seconds
        setInterval(updateDashboard, 10000);
      });
    </script>
  </body>
</html>
